package indi.wshape1.takeawaydeliveryinfo.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author Wshape1
 * @version 1.0
 * @description 第一次访问创建session并添加Cookie
 * @since 2023-01-20
 */

public class FirstVisitInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        if (session.isNew()) {
            Cookie cookie = new Cookie("JSESSIONID", URLEncoder.encode(session.getId(), StandardCharsets.UTF_8));
            cookie.setMaxAge(48 * 60 * 60);
            cookie.setPath("/");

            response.addCookie(cookie);
        }
        return true;
    }
}
